<?php
require_once(__PHY_LIB.'/class/Item.class.php');
require_once(__PHY_LIB.'/func/Server.func.php');
require_once(__PHY_LIB.'/class/uWorkSku.class.php');

class uWork extends Item {
/// definition and constructor ///
    function uWork($id=0, $field="") {
        Query::Query();
        $this->cfgKeyField("id");
        $this->cfgAllField("id,owner_id,category_id,has_size,price,price_en,title,title_en,description,description_en,tags,year,year_en,size,size_en,weight,weight_en,thumb,time_added,time_updated");
        $this->cfgTable("unit_work");
        if ("" == $field || "*" == $field) {
            $this->cfgField($this->mAllField);
        }
        else {
            $this->cfgField($field);
        }
        if (0 < $id) {
            $this->cfgWhere($this->mKeyField . "=" . $id);
            $this->load();
        }
        else {
            $this->set($this->mKeyField, $id);
        }
    }

    function invalid() {
        if (!$this->get('title')) {
            return 'title';
        }

        return false;
    }

	function setSku($nSizeID=0, $nKuangID=0, $rSku=array()) {
		if (!(0 < $this->getID())) { return false; }
		$oSku = new uWorkSku();
		$oSku->set('work_id', $this->getID());
		$oSku->set('size_id', $nSizeID);
		$oSku->set('kuang_id', $nKuangID);
		$oSku->create('work_id,size_id,kuang_id');
		if (isset($rSku['price']))        { $oSku->set('price', $rSku['price']); }
		if (isset($rSku['price_en']))     { $oSku->set('price_en', $rSku['price_en']); }
		if (isset($rSku['stock']))        { $oSku->set('stock', $rSku['stock']); }
		if (isset($rSku['stock_locked'])) { $oSku->set('stock_locked', $rSku['stock_locked']); }
		if (isset($rSku['stock_max']))    { $oSku->set('stock_max', $rSku['stock_max']); }
		$oSku->update();
	}
	function getSku($nSizeID=0, $nKuangID=0, $bMerge=false) {
		if (!(0 < $this->getID())) { return false; }
		$oSku = new uWorkSku();
		$oSku->loadUnique(array(
			'work_id' => $this->getID(),
			'size_id' => $nSizeID,
			'kuang_id' => $nKuangID,
		));
		if (0 < $oSku->getID()) {
			if ($bMerge) {
				$this->set('price', $oSku->get('price'));
				$this->set('price_en', $oSku->get('price_en'));
				$this->set('stock', $oSku->get('stock'));
				$this->set('stock_locked', $oSku->get('stock_locked'));
				$this->set('stock_max', $oSku->get('stock_max'));
			}
			return $oSku->getData();
		}
		else { return false; }
	}


/// 缩略图相关 ///
    function calcThumbUrl($nID, $sFile) {
		if (!(0 < $nID)) { $nID = $this->getID(); }
        if (!(0 < $nID)) { return false; }
        if (!$sFile) { return false; }
        $sNumber = str_pad($nID, 9, '0', STR_PAD_LEFT);
		$sDir = "/".substr($sNumber, 0, 3)."/".substr($sNumber, 3, 3)."/".substr($sNumber, 6, 3)."/";
		return "/work{$sDir}{$sFile}";
    }
    function saveThumb($sSrcPath) {
		ini_set('memory_limit', '512M'); // 为了图片处理，临时放开内存限制。
        /// 得到图片信息 ///
        list($nOldW, $nOldH, $nType) = getimagesize($sSrcPath);
        if (IMAGETYPE_GIF == $nType) {
			$hOld = imagecreatefromgif($sSrcPath);
			$sExt = 'gif';
        }
        elseif (IMAGETYPE_JPEG == $nType) {
            $hOld = imagecreatefromjpeg($sSrcPath);
			$sExt = 'jpg';
        }
        elseif (IMAGETYPE_PNG == $nType) {
            $hOld = imagecreatefrompng($sSrcPath);
			$sExt = 'png';
        }
		else { return false; } // 只支持gif/jpg/png
		/// 保存源文件 ///
		if (!($sUrl = $this->calcThumbUrl(null, "source.{$sExt}"))) { return false; }
		mkdir_plus(dirname(__PHY_STO.$sUrl)); // 生成目录
		move_uploaded_file($sSrcPath, __PHY_STO.$sUrl); // 保存
		$sSrcPath = __PHY_STO.$sUrl;
		/// 生成图片 ///
		$rTypes = array(
			'166x166.jpg',
			'50x50.jpg',
		);
		$cnt = 0;
		foreach ($rTypes as $sFile) {
			if (!($sUrl = $this->calcThumbUrl(null, $sFile))) { continue; }
			mkdir_plus(dirname(__PHY_STO.$sUrl)); // 生成目录
			preg_match('/^(\d+)x(\d+)\.(\w+)$/', $sFile, $r);
			list($x, $nNewW, $nNewH, $sExt) = $r;
			$hNew = imagecreatetruecolor($nNewW, $nNewH);
			$cWhite = imagecolorallocate($hNew, 255, 255, 255);
			imagefilledrectangle($hNew, 0, 0, $nNewW, $nNewH, $cWhite); // 画一个白底
			list($fRangeW, $fRangeH) = scale_rectangle(array($nNewW, $nNewH), array($nOldW, $nOldH), 'IN', 'EQUAL'); // 从原始图中算的copy范围
			imagecopyresampled($hNew, $hOld,
				0, 0, round(($nOldW - $fRangeW)/2), round(($nOldH - $fRangeH)/2),
				$nNewW, $nNewH, round($fRangeW), round($fRangeH));
			imagejpeg($hNew, __PHY_STO.$sUrl); // 保存
			imagedestroy($hNew);
			$cnt++;
		}
		imagedestroy($hOld);
		/// 标记已有图片 ///
		if ($cnt == sizeof($rTypes)) {
        	$this->set('thumb', 1);
			return true;
		}
		else { return false; }
	}
} /// end class uWork.


class uWorkList extends ItemList {
    /// definition and constructor ///
    function uWorkList($tablename=null) {
        ItemList::ItemList();
        $this->cfgClass("uWork");
        $this->cfgKeyField("id");
        $this->cfgAllField("id,owner_id,category_id,has_size,price,price_en,title,title_en,description,description_en,tags,year,year_en,size,size_en,weight,weight_en,thumb,time_added,time_updated");
        $this->cfgTable(null == $tablename ? "unit_work" : $tablename);
    }

} /// end class uWorkList.


/// related functions ///
function uWork_thumb($bHasThumb, $nID, $sFile) {
	if ($bHasThumb) {
		$sUrl = uWork::calcThumbUrl($nID, $sFile);
	}
	else { $sUrl = "/work/default/{$sFile}"; }
	return __DIR_STO.$sUrl;
}
function uWork_i18n($nID, $sField) {
	static $rCache = array();
	if (is_array($nID)) {
		$rCache['This'] = $nID;
	}
	elseif (!isset($rCache[$nID])) {
		$oOne = new uWork($nID);
		$rCache[$nID] = $oOne->getData();
		$rCache['This'] =& $rCache[$nID];
	}
	else {
		$rCache['This'] =& $rCache[$nID];
	}
	if ('en' == $_SESSION['LANG']) {
		$sField .= '_en';
		return $rCache['This'][$sField];
	}
	else { return $rCache['This'][$sField]; }
}
function uWork_price($rWork) {
	if ('dollor' == $_SESSION['MONEY']) { // 美元
		return $rWork['price_en'];
	}
	else { // 人民币
		return $rWork['price'];
	}
}

?>
